<?php
/**
 * Created by PhpStorm.
 * User: jimmyhsu
 * Date: 2016/10/18
 * Time: 下午2:30
 */
include ("conn.php");
$name = $_POST['name'];
$deviceId = $_POST['deviceid'];
$checkSql = "select * from userinfo where name='$name' and deviceid='$deviceId'";
$checkRs = mysql_query($checkSql);
if (mysql_num_rows($checkRs) <= 0) {
    die("invalid request");
} else {
    $checkRow = mysql_fetch_array($checkRs);
    $userid = $checkRow['id'];
    $userimage = $checkRow['image'];
}
$time = time() * 1000;
$title = $_POST['title'];
$description = $_POST['description'];
$price = $_POST['price'];
$contact = $_POST['contact'];
$itemCondition = $_POST['condition'];
$postage = $_POST['postage'];
$count = $_POST['count'];
$link = $_POST['link'];
$imgCount = $_POST['imgCount'];
$sql = "insert into secondhandtb (id, title, description, imageurls, time, price, userid, username, userimage
, contact, itemcondition, postage, count, sold, link) values (NULL, '$title', '$description', '', $time, $price, 
 $userid, '$name',  '$userimage', '$contact', $itemCondition, $postage, $count, 0, '$link')";
mysql_query($sql) or die("fail");
$insertId = mysql_insert_id();
$uploads_dir = "C:\PHPWAMP\wwwroot\phpprojects\image";
$imageUrls = "";
for ($i = 1; $i <= $imgCount; $i++) {
    if ((($_FILES["file".$i]["type"] == "image/jpeg")
            || ($_FILES["file".$i]["type"] == "image/jpg")
            || ($_FILES["file".$i]["type"] == "image/png"
			)))
    {
        if ($_FILES["file".$i]["error"] > 0)
        {
            echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
        }
        else
        {
            $name = basename($_FILES["file".$i]["name"]);
            $extension = pathinfo("$uploads_dir/$name", PATHINFO_EXTENSION);
            move_uploaded_file($_FILES["file".$i]["tmp_name"],
                $uploads_dir."\\".$insertId."-".$i.'.'.$extension);
			if ($i > 1) {
				$imageUrls = $imageUrls.";";
			}
			$imageUrls = $imageUrls."image/".$insertId."-".$i.'.'.$extension;
        }
    }
    else
    {
        echo "Invalid file".$_FILES["file".$i]["type"];
    }
}
$sql = "update secondhandtb set imageurls='$imageUrls' where id=$insertId";
mysql_query($sql) or die("fail");
//foreach ($_FILES["imgFile"]["error"] as $key=>$error) {
//    if ($error == UPLOAD_ERR_OK) {
//        $tmp_name = $_FILES["pictures"]["tmp_name"][$key];
//        // basename() may prevent filesystem traversal attacks;
//        // further validation/sanitation of the filename may be appropriate
//        $name = basename($_FILES["pictures"]["name"][$key]);
//        $extension = pathinfo("$uploads_dir/$name", PATHINFO_EXTENSION);
//        move_uploaded_file($tmp_name, "$uploads_dir/$insertId"."-".$i.".".$extension);
//        $i++;
//    }
//}
echo "success";
//move_uploaded_file($_FILES['imgFile']['tmp_name'], "image/".$_FILES["file"]["name"]);